﻿
using System;
using KBEngine;
using UnityEngine;

public partial class NetGame : MonoBehaviour
{
	#region Instance Mode
    private static NetGame _instance;
    public static NetGame Inst
    {
        get
        {
			if(_instance == null)
            {
                UnityEngine.GameObject netGame = new UnityEngine.GameObject("NetwokManager");
                _instance = netGame.AddComponent<NetGame>();
            }
            return _instance;
        }
    }
	#endregion

    private bool startRelogin = false;

    public void InstallCommon()
    {
        // common
        KBEngine.Event.registerOut("onKicked", this, "onKicked");
        KBEngine.Event.registerOut("onDisconnected", this, "onDisconnected");
        KBEngine.Event.registerOut("onConnectionState", this, "onConnectionState");
    }

	public void RemoveCommon()
    {
        KBEngine.Event.deregisterOut(this);
    }


	public void info(object msg)
    {
        Debug.Log(msg);
    }

	public void err(object msg)
    {
        Debug.LogError(msg);
    }


    public void onKicked(UInt16 failedcode)
    {
        //Debug.Log("kick, disconnect!, reason=" + KBEngineApp.app.serverErr(failedcode));
        //Application.LoadLevel("login");
        //ui_state = 0;
    }

    public void onDisconnected()
    {
        info("disconnect! will try to reconnect...(你已掉线，尝试重连中!)");
        startRelogin = true;
        Invoke("onReloginBaseappTimer", 1.0f);
    }

    public void onReloginBaseappTimer()
    {
        //if (ui_state == 0)
        //{
        //    err("disconnect! (你已掉线!)");
        //    return;
        //}

        KBEngineApp.app.reloginBaseapp();

        if (startRelogin)
            Invoke("onReloginBaseappTimer", 3.0f);
    }

    public void onConnectionState(bool success)
    {
        if (!success)
            err("connect(" + KBEngineApp.app.getInitArgs().ip + ":" + KBEngineApp.app.getInitArgs().port + ") is error! (连接错误)");
        else
            info("connect successfully, please wait...(连接成功，请等候...)");
    }
}